

#import "ShopMenuController.h"
#import "DishManager.h"
#import "Dish.h"
#import "Constants.h"
#import "MobClick.h"
#import "FMDBDishManager.h"
#import "DishItem.h"

@interface ShopMenuController () <UIFolderTableViewDelegate>
@end

@implementation ShopMenuController
@synthesize styleOfCookingList;
@synthesize dishCategories;
@synthesize currentDishCategory;
@synthesize leftTable;
@synthesize rightTable;
@synthesize isTouched;
@synthesize phoneAry;
@synthesize filePath5;
@synthesize filePath6;
@synthesize filePath7;
@synthesize countDictionary;
@synthesize countNumLab;
@synthesize priceLab;
@synthesize allDishesDictionary;
@synthesize folderTableView;
//@synthesize sampleFolder1 = _sampleFolder1;
//@synthesize sampleFolder2 = _sampleFolder2;
//@synthesize sampleFolder3 = _sampleFolder3;
//@synthesize sampleFolder4 = _sampleFolder4;
//@synthesize sampleFolder5 = _sampleFolder5;
//@synthesize sampleFolder6 = _sampleFolder6;

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//加载指示器
-(void)showHUD{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate = self;
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)myTask {

//    leftTable = [[[UITableView alloc] initWithFrame:CGRectMake(0, 25, 90, 342)] autorelease];
//    //设置cell为无边框
//    leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;   
//    //设置滚动条的位置
//    leftTable.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, leftTable.bounds.size.width-7);
//    leftTable.delegate = self;
//    leftTable.dataSource = self;
//    leftTable.tag = 1;
//    //减慢tableview的滚动速度，正常值为1.f
//    leftTable.decelerationRate=0.5f;
//
//    rightTable = [[[UITableView alloc] initWithFrame:CGRectMake(90, 25, 230, 342)] autorelease]; 
//    rightTable.hidden=YES;
//    rightTable.delegate = self;
//    rightTable.dataSource = self;
//    //设置不显示滚动条
//    rightTable.showsVerticalScrollIndicator=YES;
//    rightTable.tag = 2;
//    //减慢tableview的滚动速度，正常值为1.f
//    rightTable.decelerationRate=0.5f;
//    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"leftPanelBg" ofType:@"png"];
//    UIImageView *bgView = [[[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]] autorelease];
//    [leftTable setBackgroundView:bgView];
////    [bgView release];
//    [self.view addSubview:leftTable];
//    [self.view addSubview:rightTable];
    
    //从后台获取所需的数据
    DishManager *manager = [[DishManager alloc] init];
    dishCategories = [manager getAllDishesBySupId:(NSString *)[recieveDictionary objectForKey:@"supId"]];
//    fmdbDishManager=[[FMDBDishManager alloc]init];
//    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
//    if([appDelegate status])
//    {
        //联网，添加到本地
//        dishCategories = [manager getAllDishesBySupId:(NSString *)[recieveDictionary objectForKey:@"supId"]];
//        //插入本地
//        NSInteger supid=[[recieveDictionary objectForKey:@"supId"]intValue];
//        [fmdbDishManager insertAllDishesBySupIdToLoc:dishCategories supplierid:supid];
//    }
//    else{
//        dishCategories=[fmdbDishManager getAllDishesBySupIdFromLoc:[recieveDictionary objectForKey:@"supId"]];
//    }
//    [fmdbDishManager release];

    
    if(dishCategories.count==0||dishCategories==nil){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络不稳定请重试" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertView.tag=2;
        [alertView show];
    }
    else{
        

    phoneAry=[recieveDictionary objectForKey:@"phoneArray"];
    //设置页面所要显示的数据信息
    if([dishCategories count]==0)
    {
        currentDishCategory=Nil;   
    }
    else
    {
        currentDishCategory = (DishCategory *)[dishCategories objectAtIndex:0];
    }
    self.styleOfCookingList = dishCategories;
    
    //用来放入已显示过的dish对象
    allDishesDictionary = [NSMutableDictionary dictionary];
    //将显示过的dish对象保存起来
    for (Dish *dishObject in currentDishCategory.dishes) {
        if([[dishObject dishItems] count] == 0){
            [allDishesDictionary setObject:dishObject forKey:[[NSString alloc] initWithFormat:@"%d",dishObject.dishId]];
        }
        else{
            for(DishItem *dishItem in dishObject.dishItems){
                Dish *tempDish = [[Dish alloc] init];
                tempDish.dishId = dishItem.dishItemId;
                //有区分冷热，也有区分大小
                if([dishItem.type length] > 0 && [dishItem.size length] > 0){
                    tempDish.dishName = [[NSString alloc] initWithFormat:@"%@(%@  %@)",dishObject.dishName,dishItem.type,dishItem.size];
                }
                //区分冷热，但不区分大小
                else if([dishItem.type length] > 0 && [dishItem.size length] == 0){
                    tempDish.dishName = [[NSString alloc] initWithFormat:@"%@(%@)",dishObject.dishName,dishItem.type];
                }
                //不区分冷热，但区分大小
                else{
                    tempDish.dishName = [[NSString alloc] initWithFormat:@"%@(%@)",dishObject.dishName,dishItem.size];
                }
                tempDish.price = dishItem.price;
                [allDishesDictionary setObject:tempDish forKey:[[NSString alloc] initWithFormat:@"%d",dishItem.dishItemId]];
            }
        }
    }
    
    //设置价格
    
//    Dish *dish =  [currentDishCategory.dishes objectAtIndex:row];
    
    
//    [manager release];
    [leftTable reloadData];
    leftTable.hidden=NO;
    //默认选中左侧第一个
    NSIndexPath *first = [NSIndexPath indexPathForRow:0 inSection:0];
    //当没有菜单的时候不会闪退
    if([dishCategories count]!=0)
    {
        [leftTable selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    [rightTable reloadData];
    rightTable.hidden=NO;
    //countDictionary用来保存选择菜品数量后保存菜品ID和数量的键值对
    countDictionary = [NSMutableDictionary dictionary];
    
    NSString *source = (NSString *)[recieveDictionary objectForKey:@"source"];
    //统计点击过查看菜单按钮的商家数据到友盟
    if(source == @"detailShopShowMenuNew"){
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              (NSString *)[recieveDictionary objectForKey:@"supId"],@"商家ID",(NSString *)[recieveDictionary objectForKey:@"supName"],@"商家名称", nil];
        [MobClick event:@"detailShopShowMenuNew" attributes:dict];
    }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer; 
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    //打电话
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    self.navigationController.navigationBarHidden = NO; 
    //设置视图title
    self.title= [recieveDictionary objectForKey:@"supName"];
    //设置返回上一页按钮
    //第一个参数为按钮标题
    //第二个参数是按钮样式
    //第三个参数接受消息的对象
    //第四个参数是按钮的回调函数
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [leftButton addTarget:self action:@selector(backButtonPressdDelay) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //设置为左边按钮
    [[self navigationItem] setLeftBarButtonItem:leftItem];
    
    //定义导航栏右侧按钮
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navRightBtn" ofType:@"png"];
    [rightButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [rightButton setTitle:@"确 定" forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
//    [rightButton addTarget:self action:@selector(phoneCall) forControlEvents:UIControlEventTouchUpInside];
    [rightButton addTarget:self action:@selector(addToShoppingCart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置为右边按钮
    [[self navigationItem] setRightBarButtonItem:rightItem];

    //顶部显示的已点数量和价格
    NSString *filePath4=[[NSBundle mainBundle] pathForResource:@"topBg" ofType:@"png"];
    UIImageView *topView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath4]];
    [topView setFrame:CGRectMake(0, -5, 320, 30)];
    
    //生成显示点菜份数文字的label
    UILabel *countTextNumLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 70, 20)];
    countTextNumLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    countTextNumLab.text = @"共计         份";
    countTextNumLab.textColor = [UIColor whiteColor];
    countTextNumLab.backgroundColor=[UIColor clearColor];
    //生成显示点菜份数数字的label
    countNumLab = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 30, 20)];
    countNumLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    countNumLab.text = @"0";
    countNumLab.textColor = [UIColor redColor];
    countNumLab.backgroundColor=[UIColor clearColor];
    //生成显示点菜价格文字的label
    UILabel *priceTextLab = [[UILabel alloc] initWithFrame:CGRectMake(200, 0, 110, 20)];
    priceTextLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    priceTextLab.text = @"总计                     元";
    priceTextLab.textColor = [UIColor whiteColor];
    priceTextLab.backgroundColor=[UIColor clearColor];
    //生成显示点菜价格数字的label
    priceLab = [[UILabel alloc] initWithFrame:CGRectMake(245, 0, 50, 20)];
    priceLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    priceLab.text = @"0.00";
    priceLab.textColor = [UIColor redColor];
    priceLab.backgroundColor=[UIColor clearColor];
    
    [self.view addSubview:topView];
    [self.view addSubview:countTextNumLab];
    [self.view addSubview:countNumLab];
    [self.view addSubview:priceTextLab];
    [self.view addSubview:priceLab];
    
    NSInteger tempHeight=SSiphoneType==0?342:342+IOS5HEIGHT;
    leftTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 25, 90, tempHeight)];
    //设置cell为无边框
    leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;   
    //设置滚动条的位置
    leftTable.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, leftTable.bounds.size.width-7);
    leftTable.delegate = self;
    leftTable.dataSource = self;
    leftTable.tag = 1;
    //减慢tableview的滚动速度，正常值为1.f
    leftTable.decelerationRate=0.5f;
    
    rightTable = [[UIFolderTableView alloc] initWithFrame:CGRectMake(90, 25, 230, tempHeight)];
    rightTable.hidden=YES;
    rightTable.delegate = self;
    rightTable.dataSource = self;
    //设置不显示滚动条
    rightTable.showsVerticalScrollIndicator=YES;
    rightTable.tag = 2;
    //减慢tableview的滚动速度，正常值为1.f
    rightTable.decelerationRate=0.5f;
    NSString *filePath8=[[NSBundle mainBundle] pathForResource:@"leftPanelBg" ofType:@"png"];
    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath8]];
    [leftTable setBackgroundView:bgView];
    [self.view addSubview:leftTable];
    [self.view addSubview:rightTable];

    
    
    filePath5=[[NSBundle mainBundle] pathForResource:@"defaultBg" ofType:@"png"];
    filePath6=[[NSBundle mainBundle] pathForResource:@"touchBg" ofType:@"png"];
    filePath7=[[NSBundle mainBundle] pathForResource:@"selectBg" ofType:@"png"];
    
    folderTableView = [[UIFolderTableView alloc] init];
    [self showHUD];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    isTouched=YES;
    //统计菜单页面停留的时间到友盟（此处是开始计算的代码）
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [recieveDictionary objectForKey:@"supId"],@"商家ID",[recieveDictionary objectForKey:@"supName"],@"商家名称", nil];
    [MobClick beginEvent:@"shopMenuStayTimeNew" primarykey:@"m1" attributes:dict];
}

-(void)viewWillDisappear:(BOOL)animated
{
    //统计菜单页面停留的时间到友盟（此处是结束计算的代码）
    [MobClick endEvent:@"shopMenuStayTimeNew" primarykey:@"m1"];
}

- (void)backButtonPressdDelay{
    if(isTouched){
        isTouched=NO;
        
        NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
        SystemSoundID system_sound_id;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
        AudioServicesPlaySystemSound(system_sound_id);
        
        [self performSelector:@selector(backButtonPressd) withObject:NULL afterDelay:0.1];
    }
}



- (void)backButtonPressd{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

//添加到购物车
-(void)addToShoppingCart{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [folderTableView closePerformByMyself];//关闭右侧tableview的cell的下拉页面
    NSMutableArray *dishesArray = [[NSMutableArray alloc] init];
    NSDictionary *shopInfoDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[recieveDictionary objectForKey:@"supId"],@"shopId",[recieveDictionary objectForKey:@"supName"],@"shopName",phoneAry,@"phoneNumber", nil];
    //得到词典中所有KEY值
    NSEnumerator * enumeratorKey = [countDictionary keyEnumerator];
    //快速枚举遍历所有KEY的值
    for (NSString *keyValue in enumeratorKey) {
        Dish *dish = [allDishesDictionary objectForKey:keyValue];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              keyValue,@"dishId",dish.dishName,@"dishName",[countDictionary objectForKey:keyValue],@"dishNumber",[[NSString alloc] initWithFormat:@"%f",dish.price],@"dishPrice",[recieveDictionary objectForKey:@"supId"],@"shopId",nil];
        [dishesArray addObject:dict];
    }
    UIAlertView *alert;
    if([dishesArray count] > 0){
        FMDBDishManager *fmdbDishManager = [[FMDBDishManager alloc] init];
        Boolean insertShopReturnValue = [fmdbDishManager insertShopsToShoppingCart:shopInfoDictionary];
        Boolean insertDishReturnValue = [fmdbDishManager insertDishesToShoppingCart:dishesArray];
        if(insertShopReturnValue && insertDishReturnValue){
            alert = [[UIAlertView alloc] initWithTitle:@"提  示" message:@"已保存到购物车" delegate:self cancelButtonTitle:@"确  定" otherButtonTitles:nil];
        }
        else{
            alert = [[UIAlertView alloc] initWithTitle:@"提  示" message:@"添加到购物车失败，请重试" delegate:self cancelButtonTitle:@"确  定" otherButtonTitles:nil];
        }
        [alert show];
        //将当前视图推出栈，程序将进入上一视图
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        alert = [[UIAlertView alloc] initWithTitle:@"提  示" message:@"您还未点菜哦~" delegate:self cancelButtonTitle:@"确  定" otherButtonTitles:nil];
        [alert show];
    }
}

-(void)phoneCall{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    for(NSString *phone in phoneAry){
        [alert addButtonWithTitle:phone];
    }
    alert.tag = 1;
    //统计拨打电话按钮被点击的次数到友盟
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [recieveDictionary objectForKey:@"supId"],@"商家ID",[recieveDictionary objectForKey:@"supName"], @"商家名称",nil];
    [MobClick event:@"shopMenuCallButtonNew" attributes:dict];
    
	[alert show];
}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number]; 
        //统计拨打电话的次数到友盟
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              [recieveDictionary objectForKey:@"supId"],@"商家ID",[recieveDictionary objectForKey:@"supName"],@"商家名称", nil];
        [MobClick event:@"shopCallActionNew" attributes:dict];
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 
    }
    //网络不通，返回上页
    if(alertView.tag==2){
        //将当前视图推出栈，程序将进入上一视图
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    //打电话
    if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        [self phoneCall];
    }
}



//- (void)rootButtonPressd{
//    //直接进入根视图
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}




//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag==1){
        return [dishCategories count];
    }else{
        return [currentDishCategory.dishes count];
    }
    [self viewDidLoad];
}

//滚动的过程无法点击左侧菜品类型按钮
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    leftTable.allowsSelection=NO;
}
//滚动结束后可以点击
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    leftTable.allowsSelection=YES;
}


//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 1)
    {
        static NSString *identifier = @"TypeIdentifier";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        NSUInteger row = [indexPath row];
        DishCategory *dishCategory = (DishCategory *)[styleOfCookingList objectAtIndex:row];
        cell.textLabel.text = dishCategory.dishCategoryName;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:15];

        cell.textLabel.textAlignment = UITextAlignmentCenter;
        
        [cell setTag:dishCategory.dishCategoryId];
        
        
        

        UIImageView *defaultBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath5]];

        UIImageView *touchBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath6]];

        UIImageView *selectBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath7]];
        
        [cell setBackgroundView:defaultBgView];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectedBackgroundView = touchBgView;
        cell.editingAccessoryView = selectBgView;
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"DishCellIdentifier";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }else {
            RemoveAllSubViews(cell.contentView);
        }
        
        NSInteger row = [indexPath row];
        Dish *dish =  [currentDishCategory.dishes objectAtIndex:row];
        UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:100];
        if (nameLabel == nil) {
            nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 14)];
            nameLabel.opaque=YES;
            [nameLabel setText:dish.dishName];
            [nameLabel setFont:[UIFont boldSystemFontOfSize:14]];
            nameLabel.tag = 100;
            [cell.contentView addSubview:nameLabel];
        }
        NSInteger dishCount = 0;//用来统计已点数量的参数
        //菜品没有类别时
        if([dish.dishItems count] == 0){
            UILabel *priceLabel = (UILabel *)[cell.contentView viewWithTag:200];
            if (priceLabel == nil) {
                priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 35, 210, 12)];
                priceLabel.opaque=YES;
                //如果价格为0，显示备注
                if(dish.price == 0){
                    NSString *priceToStr=[[NSString alloc]initWithFormat:@"%@",dish.desc];
                    [priceLabel setText:priceToStr];
                }
                else{
                    NSString *priceToStr=[[NSString alloc]initWithFormat:@"¥ %0.2f",dish.price];
                    [priceLabel setText:priceToStr];
                }
                [priceLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                [priceLabel setFont:[UIFont boldSystemFontOfSize:12]];
                priceLabel.tag = 200;
                [cell.contentView addSubview:priceLabel];
            }
            dishCount = [[countDictionary objectForKey:[[NSString alloc] initWithFormat:@"%d",dish.dishId]] intValue];
        }
        //菜品有类别时
        else{
            NSString *coldPrices = [[NSString alloc] init];//分类冷的价格字符串
            NSString *hotPrices = [[NSString alloc] init];//分类热的价格字符串
            NSString *noTypePrices = [[NSString alloc] init];//不分冷热时的价格字符串
            for(DishItem *dishItem in dish.dishItems){
                //拼接分类为冷的字符串
                if([dishItem.type isEqualToString:@"冷"]){
                    if([coldPrices length] == 0){
                        if([dishItem.size length] == 0){
                            coldPrices = [[NSString alloc] initWithFormat:@"¥ %0.2f",dishItem.price];
                        }
                        else{
                            coldPrices = [[NSString alloc] initWithFormat:@"%@:¥ %0.2f",dishItem.size,dishItem.price];
                        }
                    }
                    else{
                        coldPrices = [[NSString alloc] initWithFormat:@"%@  %@:¥ %0.2f",coldPrices,dishItem.size,dishItem.price];
                    }
                }
                //拼接分类为热的字符串
                else if([dishItem.type isEqualToString:@"热"]){
                    if([hotPrices length] == 0){
                        if([dishItem.size length] == 0){
                            hotPrices = [[NSString alloc] initWithFormat:@"¥ %0.2f",dishItem.price];
                        }
                        else{
                            hotPrices = [[NSString alloc] initWithFormat:@"%@:¥ %0.2f",dishItem.size,dishItem.price];
                        }
                    }
                    else{
                        hotPrices = [[NSString alloc] initWithFormat:@"%@  %@:¥ %0.2f",hotPrices,dishItem.size,dishItem.price];
                    }
                }
                //拼接分类不是冷也不是热时的字符串
                else{
                    if([noTypePrices length] == 0){
                        if([dishItem.size length] == 0){
                            noTypePrices = [[NSString alloc] initWithFormat:@"¥ %0.2f",dishItem.price];
                        }
                        else{
                            noTypePrices = [[NSString alloc] initWithFormat:@"%@:¥ %0.2f",dishItem.size,dishItem.price];
                        }
                    }
                    else{
                        noTypePrices = [[NSString alloc] initWithFormat:@"%@  %@:¥ %0.2f",noTypePrices,dishItem.size,dishItem.price];
                    }
                }
                dishCount = dishCount + [[countDictionary objectForKey:[[NSString alloc] initWithFormat:@"%d",dishItem.dishItemId]] intValue];
            }
            //如果有冷的价格
            if([coldPrices length] > 0){
                UILabel *coldLabel = (UILabel *)[cell.contentView viewWithTag:201];
                if (coldLabel == nil){
                    if([hotPrices length] == 0){
                        coldLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 35, 210, 12)];
                    }
                    else{
                        coldLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 210, 12)];
                    }
                    coldLabel.opaque=YES;
                    [coldLabel setText:[[NSString alloc] initWithFormat:@"冷: %@",coldPrices]];
                    [coldLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                    [coldLabel setFont:[UIFont boldSystemFontOfSize:12]];
                    coldLabel.tag = 201;
                    [cell.contentView addSubview:coldLabel];
                }
            }
            //如果有热的价格
            if([hotPrices length] > 0){
                UILabel *hotLabel = (UILabel *)[cell.contentView viewWithTag:202];
                if(hotLabel == nil){
                    if([coldPrices length] == 0){
                        hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 35, 210, 12)];
                    }
                    else{
                        hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 45, 210, 12)];
                    }
                    hotLabel.opaque=YES;
                    [hotLabel setText:[[NSString alloc] initWithFormat:@"热: %@",hotPrices]];
                    [hotLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                    [hotLabel setFont:[UIFont boldSystemFontOfSize:12]];
                    hotLabel.tag = 202;
                    [cell.contentView addSubview:hotLabel];
                }
            }
            //如果有不区分冷热的价格
            if([noTypePrices length] > 0){
                UILabel *noTypeLabel = (UILabel *)[cell.contentView viewWithTag:203];
                if (noTypeLabel == nil){
                    noTypeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 35, 210, 12)];
                    noTypeLabel.opaque=YES;
                    [noTypeLabel setText:noTypePrices];
                    [noTypeLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                    [noTypeLabel setFont:[UIFont boldSystemFontOfSize:12]];
                    noTypeLabel.tag = 203;
                    [cell.contentView addSubview:noTypeLabel];
                }
            }
        }
        
        //若用户选择的数量大于0，则显示选择的数字到cell的右上角
        if(dishCount > 0){
            UILabel *countLab = [[UILabel alloc] initWithFrame:CGRectMake(205, 5, 20, 20)];
            countLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
            countLab.text = [[NSString alloc] initWithFormat:@"%d",dishCount];
            countLab.textColor = [UIColor redColor];
            countLab.backgroundColor=[UIColor clearColor];
            countLab.tag = 1;
            //往选择的菜品相应的cell右上角添加所选择的数字
            [cell.contentView addSubview:countLab];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        cell.tag = dish.dishId;
        return cell;
    }
}

//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    if(tableView.tag==1){
        return 50;
    }else{
        //此处不设置的话，rowheight为44，不知道为什么
        [tableView setRowHeight:65.0];
        return 65;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    //点击菜品分类的cell
    if(tableView.tag == 1){
        NSInteger row = [indexPath row];
        currentDishCategory = (DishCategory *)[dishCategories objectAtIndex:row];
        
        //将显示过的dish对象保存起来
        for (Dish *dishObject in currentDishCategory.dishes) {
            if([[dishObject dishItems] count] == 0){
                [allDishesDictionary setObject:dishObject forKey:[[NSString alloc] initWithFormat:@"%d",dishObject.dishId]];
            }
            else{
                for(DishItem *dishItem in dishObject.dishItems){
                    Dish *tempDish = [[Dish alloc] init];
                    tempDish.dishId = dishItem.dishItemId;
                    if([dishItem.type length] > 0){
                        tempDish.dishName = [[NSString alloc] initWithFormat:@"%@(%@  %@)",dishObject.dishName,dishItem.type,dishItem.size];
                    }
                    else{
                        tempDish.dishName = [[NSString alloc] initWithFormat:@"%@(%@)",dishObject.dishName,dishItem.size];
                    }
                    tempDish.price = dishItem.price;
                    [allDishesDictionary setObject:tempDish forKey:[[NSString alloc] initWithFormat:@"%d",dishItem.dishItemId]];
                }
            }
        }
        [folderTableView closePerformByMyself];//关闭右侧tableview的cell的下拉页面
        //[self performSelector:@selector(reloadData) withObject:NULL afterDelay:0.1];
        [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];
    }
    //点击菜单的cell
    else if(tableView.tag == 2){
        Dish *dish = [currentDishCategory.dishes objectAtIndex:indexPath.row];
        NSInteger dishId = dish.dishId;
        NSMutableDictionary *sampleFolderDic = [[NSMutableDictionary alloc] init];//用来存放sampleFolder的键值对字典
        UIView *folderView = [[UIView alloc] init];
        if([dish.dishItems count] == 0){
            //生成一个选择菜品数量的VIEW
            FolderViewController *sampleFolder = [[FolderViewController alloc] initWithNibName:NSStringFromClass([FolderViewController class]) bundle:nil];
            sampleFolder.view.tag = dishId;
            //根据菜品ID从字典里获取已经选择过的数量，如果有选择过，则显示选择过的数字，没选择过，则显示0
            NSString *hisCount = [countDictionary objectForKey:[[NSString alloc] initWithFormat:@"%d",dishId]];
            if(hisCount != nil){
                [sampleFolder setCountLabText:[hisCount intValue]];
            }
            else{
                [sampleFolder setCountLabText:0];
            }
            //设置下拉页面左侧的单价
            [sampleFolder setPriceLabText:dish.price];
            
            [sampleFolderDic setObject:sampleFolder forKey:[[NSString alloc] initWithFormat:@"%d",dishId]];
            folderView.frame = CGRectMake(0,0,320,60);
            [folderView addSubview:sampleFolder.view];
        }
        else{
            NSInteger folderViewHeight = 37;//下拉页面的高度
            NSInteger sampleFolderY = 0;//每个folder的起始Y坐标
            for(int i = 0;i<[dish.dishItems count];i++){
                DishItem *dishItem = [dish.dishItems objectAtIndex:i];
                //生成一个选择菜品数量的VIEW
                FolderViewController *sampleFolder = [[FolderViewController alloc] initWithNibName:NSStringFromClass([FolderViewController class]) bundle:nil];
                //有区分冷热，则设置描述先显示冷热，没有则直接显示大小
                if([dishItem.type length] > 0){
                    sampleFolder.desc = [[NSString alloc] initWithFormat:@"%@:%@",dishItem.type,dishItem.size];
                }
                else{
                    sampleFolder.desc = [[NSString alloc] initWithFormat:@"%@:",dishItem.size];
                }
                sampleFolder.isItem = TRUE;
                if(i == 0 && [dish.dishItems count] > 1){
                    sampleFolder.viewPosition = @"top";
                }
                else if(i > 0 && i < [dish.dishItems count]-1){
                    sampleFolder.viewPosition = @"middle";
                }
                else if(i > 0 && i == [dish.dishItems count]-1){
                    sampleFolder.viewPosition = @"bottom";
                }
                sampleFolder.view.frame = CGRectMake(0,sampleFolderY,320,37);
                sampleFolder.view.tag = dishItem.dishItemId;
                //根据菜品ID从字典里获取已经选择过的数量，如果有选择过，则显示选择过的数字，没选择过，则显示0
                NSString *hisCount = [countDictionary objectForKey:[[NSString alloc] initWithFormat:@"%d",dishItem.dishItemId]];
                if(hisCount != nil){
                    [sampleFolder setCountLabText:[hisCount intValue]];
                }
                else{
                    [sampleFolder setCountLabText:0];
                }
                //设置下拉页面左侧的单价
                [sampleFolder setPriceLabText:dishItem.price];
                
                [sampleFolderDic setObject:sampleFolder forKey:[[NSString alloc] initWithFormat:@"%d",dishItem.dishItemId]];
                sampleFolderY = sampleFolderY + 37;
                folderViewHeight = folderViewHeight + 37;
                [folderView addSubview:sampleFolder.view];
            }
            folderView.frame = CGRectMake(0,0,320,folderViewHeight - 37);
        }
        //弹出选择菜品数量的view，closeBlock是当下拉页面关闭时，调用的回调方法
        folderTableView = (UIFolderTableView *)tableView;
        [folderTableView openFolderAtIndexPath:indexPath WithContentView:folderView                                     openBlock:^(UIView *subClassView, CFTimeInterval duration, CAMediaTimingFunction *timingFunction){
                                         // opening actions
                                        //设置tableview不可滑动
                                        tableView.scrollEnabled = NO;
                                     }
                                    closeBlock:^(UIView *subClassView, CFTimeInterval duration, CAMediaTimingFunction *timingFunction){
                                        // closing actions
                                        [self onCloseFolderTableViewBlock:folderView sampleFolderDic:sampleFolderDic indexPath:indexPath];
                                    }
                               completionBlock:^{
                                   // completed actions
                                   //设置tableview可以滑动
                                   tableView.scrollEnabled = YES;
                               }];
    }
}

-(void)onCloseFolderTableViewBlock:(UIView *)folderView sampleFolderDic:(NSMutableDictionary *)sampleFolderDic indexPath:(NSIndexPath *)indexPath{
    NSInteger countAll = 0;
    for(UIView *sampleFolderView in [folderView subviews]){
        NSInteger dishId = sampleFolderView.tag;
        FolderViewController *tempFolder = [sampleFolderDic objectForKey:[[NSString alloc] initWithFormat:@"%d",dishId]];
        countAll = countAll + [tempFolder.countLab.text intValue];
        //将用户选择的数量和菜品ID保存到字典
        [countDictionary setObject:tempFolder.countLab.text forKey:[[NSString alloc] initWithFormat:@"%d",tempFolder.view.tag]];
        //如果选择的菜品数量为0，则将已保存此菜移除
        if([tempFolder.countLab.text intValue] == 0){
            [countDictionary removeObjectForKey:[[NSString alloc] initWithFormat:@"%d",tempFolder.view.tag]];
        }
    }
    
    
    
    
    //移除cell右上角已存在的数字label
    [[[rightTable cellForRowAtIndexPath:indexPath].contentView viewWithTag:1] removeFromSuperview];
    //若用户选择的数量大于0，则显示选择的数字到cell的右上角
    if(countAll > 0){
        UILabel *countLab = [[UILabel alloc] initWithFrame:CGRectMake(205, 5, 20, 20)];
        countLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
        countLab.text = [[NSString alloc] initWithFormat:@"%d",countAll];
        countLab.textColor = [UIColor redColor];
        countLab.backgroundColor=[UIColor clearColor];
        countLab.tag = 1;
        //往选择的菜品相应的cell右上角添加所选择的数字
        [[rightTable cellForRowAtIndexPath:indexPath].contentView addSubview:countLab];
    }
    
    
    NSInteger numberCount = 0;
    //得到词典中所有Value值
    NSEnumerator * enumeratorValue = [countDictionary objectEnumerator];
    //快速枚举遍历所有Value的值
    for (NSString *number in enumeratorValue) {
        //计算份数
        numberCount = numberCount + [number intValue];
    }
    //更改顶部的份数
    countNumLab.text = [[NSString alloc] initWithFormat:@"%d",numberCount];
    
    float priceCount = 0;
    //得到词典中所有KEY值
    NSEnumerator * enumeratorKey = [countDictionary keyEnumerator];
    //快速枚举遍历所有KEY的值
    for (NSString *key in enumeratorKey) {
        //根据dishId获取dish的单价
        Dish *dish = [allDishesDictionary objectForKey:key];
        float dishPrice = dish.price;
        //根据dishId获取该菜品已选择的数量
        NSInteger dishCount = [[countDictionary objectForKey:key] intValue];
        //计算价格
        priceCount = priceCount + dishCount * dishPrice;
    }
    //更改顶部的价格
    priceLab.text = [[NSString alloc] initWithFormat:@"%0.2f",priceCount];
}

-(void)reloadData{
//    [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];


}
-(void)onResponseInMainThread{

    [rightTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    leftTable.allowsSelection=YES;
    [rightTable reloadData];
}


- (void)viewDidUnload
{
    self.styleOfCookingList=nil;
    self.dishCategories=nil;
    self.currentDishCategory=nil;
    self.leftTable=nil;
    self.rightTable=nil;
    self.phoneAry=nil;
    self.filePath5=nil;
    self.filePath6=nil;
    self.filePath7=nil;
    self.countDictionary = nil;
    self.countNumLab = nil;
    self.priceLab = nil;
    self.allDishesDictionary = nil;
    self.folderTableView = nil;
//    self.sampleFolder1 = nil;
//    self.sampleFolder2 = nil;
//    self.sampleFolder3 = nil;
//    self.sampleFolder4 = nil;
//    self.sampleFolder5 = nil;
//    self.sampleFolder6 = nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}
@end
